package com.aaa.charge.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.aaa.charge.dao.*;
import com.aaa.charge.service.CareHistoryService;
import com.aaa.charge.util.HttpClient;
import com.aaa.charge.vo.PostObjectVo;
import com.aaa.charge.vo.PostObjectVo1;
import com.aaa.entity.*;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author pzs
 * @date 2023/3/27 9:41
 * @description CareHistoryServiceImpl
 */
@Service
public class CareHistoryServiceImpl implements CareHistoryService {
    @Autowired
    private CareHistoryDao careHistoryDao;
    @Autowired
    private CareOrderDao careOrderDao;
    @Autowired
    private CareOrderItemDao careOrderItemDao;

    @Resource
    private ChargeDao orderChargeDao;
    @Resource
    private ChargeItemDao orderChargeItemDao;


    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result<Map<String,Object>> findcareHistory(String regId){

        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("reg_id", regId);
        //new CareHistory实体获取一行数据
        CareHistory careHistory = careHistoryDao.selectOne(wrapper);
        if (careHistory==null){
            return new Result(200,"单号错误");
        }
        QueryWrapper<CareOrder> wrapper1=new QueryWrapper<>();
        wrapper1.eq("ch_id",careHistory.getChId());
        List<CareOrder> careOrders = careOrderDao.selectList(wrapper1);
        List<Map<String,Object>> list=new ArrayList<>();
        if(careOrders.size()>0){
            //遍历careOrders
            for (CareOrder careOrder : careOrders) {
                Map<String,Object> map1= BeanUtil.beanToMap(careOrder);
                QueryWrapper<CareOrderItem> wrapper2=new QueryWrapper<>();
                wrapper2.eq("status",0);
                wrapper2.eq("co_id",careOrder.getCoId());
                List<CareOrderItem> careOrderItems = careOrderItemDao.selectList(wrapper2);
                if (careOrderItems.size()!=0) {
                    //计算订单金额
                    Double sum = careOrderItems.stream()
                            .map(item -> item.getAmount()
                                    .doubleValue()).reduce((a, b) -> a + b).get();
                    map1.put("careOrderItems",careOrderItems);
                    map1.put("sum",sum);
                    list.add(map1);
                }
            }
        }
        if(list.isEmpty()){
            return new Result<>(200,"请输入为支付的订单Id");
        }else {
            HashMap<String, Object> map = new HashMap<>();
                map.put("careHistory", careHistory);
                map.put("list" , list);
                return new Result<>(200, "成功", map);
        }

    }
    /**
     *现金
     */
    @Transactional
    @Override
    public Result updateStatus(PostObjectVo postObjectVo) {
        String chId = postObjectVo.getOrderChargeDto().getChId();
        String orderId="ODC1";
        Random random = new Random();
        for (int i = 0; i < 18; i++) {
            orderId += String.valueOf(random.nextInt(10));
        }
        String itemId="";


        for (PostObjectVo1 postObjectVo1 : postObjectVo.getOrderChargeItemDtoList()) {
            itemId=postObjectVo1.getItemId();
            String coId = postObjectVo1.getCoId();
            String itemName = postObjectVo1.getItemName();
            BigDecimal itemPrice = BigDecimal.valueOf(Long.parseLong(postObjectVo1.getItemPrice()));
            BigDecimal itemAmount = BigDecimal.valueOf(Long.parseLong(postObjectVo1.getItemAmount()));
            String itemType = postObjectVo1.getItemType();
            Integer itemNum = Integer.valueOf(postObjectVo1.getItemNum());
            String status="1";
            OrderChargeItem orderChargeItem=new OrderChargeItem(orderId,itemId,coId,itemName,itemPrice,itemNum,itemAmount,status,itemType);
            orderChargeItemDao.insert(orderChargeItem);
        }

        //添加到收费列表
        String regId = postObjectVo.getOrderChargeDto().getRegId();
        String patientName = postObjectVo.getOrderChargeDto().getPatientName();
        BigDecimal orderAmount = BigDecimal.valueOf(postObjectVo.getOrderChargeDto().getOrderAmount());
        String payType="0";
        String orderStatus="1";
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime payTime = LocalDateTime.now();
        OrderCharge orderCharge = new OrderCharge(orderId,regId,patientName,orderAmount,createTime,payType,orderStatus,chId,payTime);
        orderChargeDao.insert(orderCharge);

        //修改状态
        for (int i=0;i<postObjectVo.getOrderChargeItemDtoList().size();i++){
            careOrderItemDao.updateStatus(postObjectVo.getOrderChargeItemDtoList().get(i).getItemId());
        }
        return new Result<>(200,"现金收费成功");
    }

    /**
     * 微信支付
     */
    @Transactional
    @Override
    public Result payWx(PostObjectVo postObjectVo) {
        //获取患者姓名
        String patientName=postObjectVo.getOrderChargeDto().getPatientName();
        //生成orderId
        String orderId="ODC";
        Random random = new Random();
        for (int i = 0; i <19 ; i++) {
            orderId+=String.valueOf(random.nextInt(10));
        }
//        String orderId1="ODC1";
//        for (int i = 0; i <19 ; i++) {
//            orderId1+=String.valueOf(random.nextInt(10));
//        }
        //获取总金额
        BigDecimal orderAmount = BigDecimal.valueOf(postObjectVo.getOrderChargeDto().getOrderAmount());
        try {
            //设置请求的参数
            Map<String, String> params = new HashMap<>();//请求参数
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("body", patientName);//标题
            params.put("out_trade_no", orderId);
            //支付金额0.01 未来换成真是的金额
            params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
            params.put("spbill_create_ip", "127.0.0.1");//未来写成项目部署的ip
            params.put("notify_url", "http:localhost:8080/charge/docharge");
            params.put("trade_type", "NATIVE");
            //创建httpClient对象 作用远程调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //支持https协议
            client.setHttps(true);
            //设置请求参数
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            client.post();
            //获取请求的响应结果
            String content = client.getContent();

            Map<String, String> map = WXPayUtil.xmlToMap(content);

            if (map.get("result_code").equals("SUCCESS")){
                Map<String,Object> result=new HashMap<>();
                result.put("codeUrl",map.get("code_url"));
                result.put("price",orderAmount);
                result.put("orderId",orderId);

                //获取挂号单id
                String regId=postObjectVo.getOrderChargeDto().getRegId();
                //创建时间
                LocalDateTime createTime = LocalDateTime.now();

                String payType="1";
                String orderStatus="0";
                LocalDateTime payTime = LocalDateTime.now();
                String chId = postObjectVo.getOrderChargeDto().getChId();
                //将前端传过来的数据存在收费表 his_order_charge
                OrderCharge orderCharge = new OrderCharge(orderId,regId,patientName,orderAmount,createTime,payType,orderStatus,chId,payTime);

                orderChargeDao.insert(orderCharge);
                //获取itemId  修改支付状态
                List<PostObjectVo1> orderChargeItemDtoList = postObjectVo.getOrderChargeItemDtoList();
                for (int i=0;i<orderChargeItemDtoList.size();i++){
                    //创建订单后  修改开诊细表状态为已完成  his_care_order_item
                    careOrderItemDao.updateByZFBStatus(orderChargeItemDtoList.get(i).getItemId());
                }
                for (PostObjectVo1 postObjectVo1 : orderChargeItemDtoList) {
                    String itemId=postObjectVo1.getItemId();
                    String coId = postObjectVo1.getCoId();
                    String itemName = postObjectVo1.getItemName();
                    BigDecimal itemPrice = BigDecimal.valueOf(Long.parseLong(postObjectVo1.getItemPrice()));
                    BigDecimal itemAmount = BigDecimal.valueOf(Long.parseLong(postObjectVo1.getItemAmount()));
                    String itemType = postObjectVo1.getItemType();
                    Integer itemNum = Integer.valueOf(postObjectVo1.getItemNum());
                    String status="0";
                    //生成二维码 将数据存放在收费表查看弹层的支付订单详情页 his_order_charge_item
                    OrderChargeItem orderChargeItem=new OrderChargeItem(orderId,itemId,coId,itemName,itemPrice,itemNum,itemAmount,status,itemType);
                    orderChargeItemDao.insert(orderChargeItem);
                }
                return new Result(200,"生成二维码成功",result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(200,"订单失效了",null);
    }
    //查询订单是否支付
    @Override
    public Result payStatus(String orderId) {
        try {
            //根据订单状态查询微信的支付的状态
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", orderId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            client.post();
            String content = client.getContent();


            Map<String, String> map = WXPayUtil.xmlToMap(content);


            String tradeState = map.get("trade_state");
            if (tradeState.equals("SUCCESS")){ //二维码支付成功 开始修改订单

                QueryWrapper<OrderCharge> wrapper = new QueryWrapper<>();
                wrapper.eq("order_id", orderId);
                List<OrderCharge> orderCharges = orderChargeDao.selectList(wrapper);
                for (int i = 0; i < orderCharges.size(); i++) {
                    int a = orderChargeDao.updateByIdOrderCharge(orderId);
                    return new Result(200,"支付成功",a>0?true:false);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new Result(200,"请重新扫描二维码支付",false);
    }

}
